package com.cherry.ndkdemo;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity {

    static {
        System.loadLibrary("native-lib");
    }

    private SurfaceView mVideoView;
    private SurfaceHolder mSurfaceHolder;
    private ExecutorService mThreadPool;
    private File mDir;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "1");
        mThreadPool = Executors.newCachedThreadPool();
        ((TextView) findViewById(R.id.tv_native_text)).setText(stringFromJNI());
        mVideoView = findViewById(R.id.surface_view);
        mSurfaceHolder = mVideoView.getHolder();
        mSurfaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                mThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        FFmpegUtils.render(new File(mDir, "3.MP4").getAbsolutePath(), mSurfaceHolder.getSurface());
                    }
                });
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                mSurfaceHolder.getSurface().release();
            }
        });

        final File patchFile = new File(mDir, "patch");
        if (patchFile.exists()) {
            new AlertDialog.Builder(this)
                    .setMessage("有增量更新，是否去更新？")
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            patch(patchFile);
                        }
                    }).show();
        } else {
            Toast.makeText(getApplicationContext(), "当前没有增量更新包", Toast.LENGTH_LONG).show();
        }
    }

    @SuppressLint("StaticFieldLeak")
    private void patch(File patchFile) {
        new AsyncTask<File, Void, File>() {
            @Override
            protected File doInBackground(File... files) {
                String old = getApplication().getApplicationInfo().sourceDir;
                File newApk = new File(mDir, "new-release.apk");
                PatchUtils.patch(old, files[0].getAbsolutePath(), newApk.getAbsolutePath());
                return newApk;
            }

            @Override
            protected void onPostExecute(File file) {
                if (file.exists()) {
                    installApk(file);
                }else {
                    Toast.makeText(getApplicationContext(), "增量更新包合成失败", Toast.LENGTH_LONG).show();
                }
            }
        }.execute(patchFile);
    }

    private void installApk(File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //兼容7.0
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        } else {
            // 声明需要的临时权限
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            // 第二个参数，即第一步中配置的authorities
            String packageName = getApplication().getPackageName();
            Uri contentUri = FileProvider.getUriForFile(MainActivity.this, packageName + ".fileprovider", file);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    public void segment(View view) {
        mThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                File file = new File(mDir, "1.MP4");
                long start = System.currentTimeMillis();
                final boolean isSuccess = FileSegmentMergeUtils.diff(file.getAbsolutePath(), mDir.getAbsolutePath() + File.separator + "segment_%d.mp4", 8);
                Log.e("cherry_ndk_file", "分割文件耗时：" + ((System.currentTimeMillis() - start) / 1000) + " s");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (isSuccess) {
                            Toast.makeText(getApplicationContext(), "分割文件成功", Toast.LENGTH_LONG).show();
                        }
                    }
                });
            }
        });
    }

    public void merge(View view) {
        mThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                File file = new File(mDir, "1_new.MP4");
                long start = System.currentTimeMillis();
                final boolean isSuccess = FileSegmentMergeUtils.patch(file.getAbsolutePath(), mDir.getAbsolutePath() + File.separator + "segment_%d.mp4", 8);
                Log.e("cherry_ndk_file", "合并文件耗时：" + ((System.currentTimeMillis() - start) / 1000) + " s");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (isSuccess) {
                            Toast.makeText(getApplicationContext(), "合并文件成功", Toast.LENGTH_LONG).show();
                        }
                    }
                });
            }
        });
    }

    public void ffmpeg_test(View view) {
        mThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                File inputFile = new File(mDir, "2.MP4");
                File outputFile = new File(mDir, "2_output.yuv");
                FFmpegUtils.ffmpeg_test(inputFile.getAbsolutePath(), outputFile.getAbsolutePath());
            }
        });
    }

    public native String stringFromJNI();

    public void audio_decode(View view) {
        mThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                File inputFile = new File(mDir, "8.mp3");
                File outputFile = new File(mDir, "8.pcm");
                FFmpegUtils.audioDecode(inputFile.getAbsolutePath(), outputFile.getAbsolutePath());
            }
        });
    }

    public void audio_play(View view) {
        mThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                File inputFile = new File(mDir, "8.mp3");
                FFmpegUtils.audioPlayer(inputFile.getAbsolutePath());
            }
        });
    }

    public void fmod(View view) {
        startActivity(new Intent(this, FmodActivity.class));
    }
}
